var g_Feed;
var httpRetries = 0;
var opt_favChanArea;
var opt_availChanArea;
var opt_activePage;
var opt_activeSize;
var opt_activeNav;
var Reminder = null;
var opt_chanArray = null;
var connectivity_OK = framework.system.network.online;
var vverbose = true;
function fillchanArea(resText) {
	if (typeof resText == "string") {
		g_Feed = eval("(" + resText + ")");
	}
	var favChannels, addInArea, chan;
	for (var i = 0; i < g_Feed.channels.length; i++) {
		if (typeof g_Feed.channels[i].name == "undefined") {
			continue;
		}
		if (prefs.myChannels.length == 0 && isSubscribed(g_Feed.channels[i].name, g_Feed.channels[i].id)) {
			addInArea = opt_favChanArea;
		} else if (prefs.myChannels.grep("^" + g_Feed.channels[i].name + "$").length == 0) {
			addInArea = opt_availChanArea;
		} else {
			continue;
		}
		chan = mangleChanId(g_Feed.channels[i].name);
		item = addInArea.appendElement("<item ondblclick=\"chanDblClicked('chan_" + chan + "');\" onclick=\"chanClicked('chan_" + chan + "');\" name=\"chan_" + chan + "\"></item>");
		item.appendElement("<label align=\"left\" height=\"18\" valign=\"middle\">" + mangleEntities(g_Feed.channels[i].name) + "</label>");
	}
	for (var i = 0; i < prefs.myChannels.length; i++) {
		chan = mangleChanId(prefs.myChannels[i]);
		item = (isSubscribed(prefs.myChannels[i]) ? opt_favChanArea : opt_availChanArea).appendElement("<item ondblclick=\"chanDblClicked('chan_" + chan + "');\" onclick=\"chanClicked('chan_" + chan + "');\" name=\"chan_" + chan + "\"></item>");
		item.appendElement("<label align=\"left\" height=\"18\" valign=\"middle\">" + mangleEntities(prefs.myChannels[i]) + "</label>");
	}
}



function chooseCacheFolder() {
	var cur = options.getValue("TVTID.cache.foldername");
	var isWin = framework.runtime.osName.toLowerCase().match("windows");
	var isLinux = framework.runtime.osName.toLowerCase().match("linux");
	var isMac = !isWin && !isLinux;
	var fso = framework.system.filesystem;
	if (isWin) {
		var base = fso.GetFolder("%APPDATA%");
		base += "\\Local\\TVTid\\";
	} else if (isMac) {
		var base = "/Users/_your username_/";
	} else {
		var base = "/home/_your username_/";
	}
	var res = prompt("", cur.length > 0 ? cur : base);
	if (res == false) {
		return;
	}
	var exists = fso.FolderExists(res);
	if (exists == true) {
		alert(res + " er nu valgt");
		options.putValue("TVTID.cache.foldername", res);
	} else {
		if (isWin && res.indexOf(":") != 1 || !isWin && res.indexOf("/") != 0) {
			alert("Angiv venligst " + (isWin ? "drev" : "/") + " som det f\xC3\xB8rste");
		} else if (confirm("Stien du har valgt existerer ikke, vil du oprette folderen?")) {
			var dirs, okpath, i;
			if (isWin) {
				dirs = res.split("\\");
				okpath = "";
				for (i = 1; i < dirs.length; i++) {
					if (i == 0) {
						okpath = dirs[i] + "\\";
					} else {
						if (!fso.FolderExists(okpath + dirs[i])) {
							if (!fso.CreateFolder(okpath + dirs[i])) {
								break;
							}
						}
						okpath += dirs[i] + "\\";
					}
				}
				okpath += "\\";
			} else {
				dirs = res.substring(1).split("/");
				okpath = "/";
				for (i = 0; i < dirs.length; i++) {
					if (dirs[i].length == 0) {
						continue;
					}
					if (!fso.FolderExists(okpath + dirs[i])) {
						if (!fso.CreateFolder(okpath + dirs[i])) {
							break;
						}
					}
					okpath += dirs[i] + "/";
				}
			}
			if (!okpath.match(res)) {
				alert("Fejlede, check for rettigheder");
			} else {
				options.putValue("TVTID.cache.foldername", okpath);
			}
		}
	}
}

function chanDblClicked(id) {
	try {
		id = eval(id);
	} catch (e) {
		log(e.message + ", reason: possibly encoding of channel name");
	}
	var chan = trueChanId(id.name.replace(/chan_/, ""));
	if (/xml_favouriteChannels/.test(id.parentElement.name)) {
		prefs.myChannels = prefs.myChannels.grep("^" + chan + "$", true);
	} else {
		prefs.myChannels.grep(chan).length == 0 && prefs.myChannels.push(chan);
	}
	prefs.channels.favourites = prefs.myChannels.join(",");
	xml_favouriteChannels.removeAllElements();
	xml_availableChannels.removeAllElements();
	fillchanArea();
}

function chansortRequested(dir) {
	var cur = xml_favouriteChannels.selectedIndex;
	var max = xml_favouriteChannels.children.count;
	if (cur == -1) {
		return false;
	}
	if (cur + dir >= 0 && cur + dir < max) {
		var other = xml_favouriteChannels.children.item(cur + dir);
		prefs.myChannels[cur] = trueChanId(other.name.replace(/chan_/, ""));
		prefs.myChannels[cur + dir] = trueChanId(xml_favouriteChannels.selectedItem.name.replace(/chan_/, ""));
	} else {
		return false;
	}
	xml_favouriteChannels.removeAllElements();
	xml_availableChannels.removeAllElements();
	fillchanArea();
	xml_favouriteChannels.selectedIndex = cur + dir;
	return true;
}

function chanClicked(id) {}

function getChannels(feed) {
	var chan = [];
	for (var i = 0; i < feed.channels.length; i++) {
		chan.push(feed.channels[i].name);
	}
	return chan;
}

function createChannelArea() {
	var favChannels = "," + System.Gadget.Settings.readString("TVTID.Channel.Favourites") + ",";
	opt_availChanArea.value = "";
	for (var i = 0; i < g_Feed.channels.length; i++) {
		if (!RegExp("[^ ]" + g_Feed.channels[i].name + "[^ ]").test(favChannels)) {
			opt_availChanArea.value += g_Feed.channels[i].name + "\r\n";
		}
	}
}

function switchPage(idnr, clickedButton) {
	var cur = parseInt(opt_activePage.name.replace(/[^0-9]*/, ""));
	opt_activePage.visible = false;
	opt_activePage = eval("xml_settingsPage_" + idnr);
	opt_activePage.visible = true;
	return true;
}

function onOpen() {
	var fav = prefs.channels.favourites;
	opt_favChanArea = xml_favouriteChannels;
	opt_availChanArea = xml_availableChannels;
	opt_activePage = xml_settingsPage_0;
	opt_activePage.visible = true;
	opt_activeNav = xml_p1Nav;
	xml_maxPrograms.value = prefs.channels.maxProgramsOnRender;
	xml_maxVisible.value = prefs.channels.maxProgramsInTotal;
	xml_prPage.value = prefs.channels.maxPrPage;
	if (prefs.channels.favourites.length != 0) {
		prefs.myChannels = prefs.channels.favourites.split(",");
		g_useDefaultChannels = false;
	} else {
		g_useDefaultChannels = true;
	}
	fillchanArea(getFeed());
	Reminder = Favourites.init();
}

function onCancel() {}

function onOk() {
	prefs.myChannels = [];
	var iter = new Enumerator(xml_favouriteChannels.children), el;
	while (!iter.atEnd()) {
		el = iter.item();
		prefs.myChannels.push(trueChanId(el.name.replace("chan_", "")).trim());
		iter.moveNext();
	}
	options.putValue("TVTID.Channel.VisibleTitles", xml_maxPrograms.value ? xml_maxPrograms.value : "2");
	options.putValue("TVTID.Channel.TotalTitles", xml_maxVisible.value ? xml_maxVisible.value : "2");
	options.putValue("TVTID.Channel.TotalPrPage", xml_prPage.value ? xml_prPage.value : "4");
	options.putValue("TVTID.Channel.Favourites", prefs.myChannels.join(","));
	Favourites.saveProgramSettings();
	Sound.saveSoundSettings();
}
